package cmdb_account_management_v1

import (
	"context"

	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	"dfx_cmdb/cmdb-gateway/internal/svc"
	"dfx_cmdb/cmdb-gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertAccountInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInsertAccountInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertAccountInfoLogic {
	return &InsertAccountInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InsertAccountInfoLogic) InsertAccountInfo(req *types.InsertAccountInfoRequest) (resp *types.PublicResponse, err error) {
	// 转换 API 请求为 RPC 请求
	accountInfoList := make([]*cmdb_account_management_rpc.AccountInfo, 0, len(req.AccountInfo))
	for _, info := range req.AccountInfo {
		accountInfoList = append(accountInfoList, &cmdb_account_management_rpc.AccountInfo{
			Type:         info.Type,
			Platform:     info.Platform,
			PlatformName: info.PlatformName,
			Account:      info.Account,
			Password:     info.Password,
			Token:        info.Token,
			Accesskey:    info.Accesskey,
			Accesssecret: info.Accesssecret,
			Comment:      info.Comment,
			OtherInfo:    info.OtherInfo,
		})
	}

	grpcReq := &cmdb_account_management_rpc.InsertAccountInfoRequest{
		AccountInfo: accountInfoList,
	}

	// 调用 RPC 服务
	grpcResp, err := l.svcCtx.CmdbAccountManagementRpc.InsertAccountInfo(l.ctx, grpcReq)
	if err != nil {
		logx.Errorf("调用 RPC 服务失败: %v", err)
		return nil, err
	}

	return &types.PublicResponse{
		Message: grpcResp.Message,
	}, nil
}
